package com.cn.steam.iam.model;

import com.cn.steam.foundation.common.utils.Op;
import com.cn.steam.iam.model.po.IamPermission;
import com.google.common.collect.Sets;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author huangzz
 */
public class PermissionGrantedAuthority implements GrantedAuthority {

	private final String permission;

	public PermissionGrantedAuthority(String permission) {
		Assert.hasText(permission, "A granted authority textual representation is required");
		this.permission = permission;
	}

	public String getAuthority() {
		return this.permission;
	}

	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		} else {
			return obj instanceof PermissionGrantedAuthority ?
				StringUtils.equals(this.getPermission(), ((PermissionGrantedAuthority) obj).getPermission()) : false;
		}
	}

	public int hashCode() {
		return this.permission.hashCode();
	}

	public String getPermission() {
		return permission;
	}

	public String toString() {
		return this.permission;
	}

	public static Set<GrantedAuthority> convertFromIamPermission(List<IamPermission> iamPermissionList){
		if(Op.isEmpty(iamPermissionList)){
			return Sets.newHashSet();
		}
		return iamPermissionList.stream().map(iamPermission -> new PermissionGrantedAuthority(iamPermission.getPermissionId())).collect(Collectors.toSet());
	}
}
